﻿using LK.WebAPI.LK.WebAPI.ApiResult;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LK.WebAPI.Filter
{
    public class ExceptionFilter : IExceptionFilter
    {


        private IWebHostEnvironment _env;
        private ILogger<ExceptionFilter> _logger;

        public ExceptionFilter(IWebHostEnvironment _env, ILogger<ExceptionFilter> _logger)
        {
            this._env = _env;
            this._logger = _logger;
        }

        public void OnException(ExceptionContext context)
        {
            Console.WriteLine("OnException");
            var _log = context.Filters.Where(c => c is LogAttribute).FirstOrDefault();
            var log = _log as LogAttribute;
            log.ex = context.Exception;
            if (context.Exception is ActionException)
            {
                //如果是自定义异常，则不做处理
                
            }
            //系统异常
            else
            {
            }


            //日志入库
            Task.Run(() => { });
            //向负责人发报警邮件，异步
            Task.Run(() => { });
            //向负责人发送报警短信或者报警电话，异步
            Task.Run(() => { });

            Exception ex = context.Exception;
            //这里给系统分配标识，监控异常肯定不止一个系统。
            //这里获取服务器ip时，需要考虑如果是使用nginx做了负载，这里要兼容负载后的ip，
            //监控了ip方便定位到底是那台服务器出故障了
            string ip = context.HttpContext.Connection.RemoteIpAddress.ToString();

            //_logger.LogError($"系统编号：{sysId},主机IP:{ip},堆栈信息：{ex.StackTrace},异常描述：{ex.Message}");
            // 定义返回类型

            var data = new ResposeStatus
            {
                Code = 0,
                Message = context.Exception.Message
            };
            var result = new JsonResult(data);
            result.StatusCode = StatusCodes.Status200OK;
            result.ContentType = "application/json;charset=utf-8";

            context.Result = result;
            context.ExceptionHandled = true;
        }
    }
}
